<style>
  .layui-table-cell .layui-table-sort {
    display: none;
  }

  .lay-query-box .query-lt {
    width: 90%;
  }

  .layui-table-view .layui-table-tool-self {
    display: flex;
    justify-content: flex-end;
    position: initial;
    margin-top: 12px;
  }
</style>

<!-- 正文开始 -->
<div class="layui-fluid">
  <div class="layui-card">
    <div class="layui-card-body">
      <!-- 头部操作栏 -->
      <div class="layui-form lay-header">
        <div class="toolbar">
          <div class="layui-form-item lay-query-content">
            <div class="lay-query-box">
              <div class="query-lt">
                <div class="layui-inline">
                  <label class="layui-form-label">出库作业编号：</label>
                  <div class="layui-input-inline">
                    <input
                      name="code" id="code"
                      class="layui-input"
                      type="text"
                      placeholder="请输入出库作业编号"
                      autocomplete="off"
                    />
                  </div>
                </div>
                <div class="layui-inline">
                  <label class="layui-form-label">申请单编号：</label>
                  <div class="layui-input-inline">
                    <input name="receiptRecordCode" class="layui-input" type="text" placeholder="请输入申请单编号" autocomplete="off" />
                  </div>
                </div>
                <div class="layui-inline">
                  <label class="layui-form-label">出库类型：</label>
                  <div class="layui-input-inline">
                    <select
                      id="queryOutTypeId"
                      name="outTypeId"
                      lay-filter="outTypeId"
                      lay-search
                      class="common-select-search"
                    ></select>
                  </div>
                </div>
                <div class="layui-inline">
                  <label class="layui-form-label w-auto">创建时间：</label>
                  <div class="layui-input-inline">
                    <input id="pTime" class="layui-input date-icon" type="text"
                           placeholder="选择创建时间"
                           autocomplete="off" readonly/>
                    <input name="startCreateTime" id="startCreateTime" style="display: none"/>
                    <input name="endCreateTime" id="endCreateTime" style="display: none"/>
                  </div>
                </div>
              </div>
              <div class="query-rt">
                <div class="layui-inline">
                  <button
                          class="layui-btn icon-btn color-green"
                          lay-filter="formSubSearchLog"
                          lay-submit
                          layui-form-keyDownSearch="true"
                  >
                    查询
                  </button>
                  <button
                          class="layui-btn icon-btn color-white"
                          lay-filter="resets"
                          lay-submit
                  >
                    重置
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="lay-btn-rows">
          <div class="lay-btn-box">
            <div class="lay-btn-lt">
              <button
                id="productStorageWorkOutAdd"
                type="button"
                class="layui-btn icon-btn color-reseda"
              >
                添加出库作业
              </button>
              <button id="storageWorkInfoBtnExport" class="layui-btn icon-btn color-green">导出</button>
            </div>
          </div>
        </div>
      </div>
      <!-- 表格 -->
      <div class="table-bor">
        <table
          class="layui-table"
          id="productStorageWorkOutTable"
          lay-filter="productStorageWorkOutTable"
        ></table>
      </div>
    </div>
  </div>
</div>

<!-- 表格操作列 -->
<script type="text/html" id="receiptRecordTabBar">
  <!-- {{# if(d.status == '1'){ }} -->
  <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="audit">审核</a>
  <!-- {{# } }} -->
  <a class="layui-btn layui-btn-xs layui-btn-primary" lay-event="detail"
    >详情</a
  >
</script>

<!-- 表单弹窗 -->
<script type="text/html" id="productStorageWorkOutForm">
  <form lay-filter="productStorageWorkOutForm" class="layui-form open-form">
    <div class="open-model">
      <div class="open-auto">
        <input name="id" type="hidden" />
        <div class="layui-col-xs4">
          <div class="layui-form-item">
            <label class="layui-form-label">出库类型</label>
            <div class="layui-input-block">
              <select
                id="outTypeId"
                name="outTypeId"
                lay-verify="required"
                lay-filter="outTypeId"
                lay-search
              ></select>
            </div>
          </div>
        </div>
        <div class="layui-col-xs4">
          <div class="layui-form-item">
            <label class="layui-form-label">出库申请单</label>
            <div class="layui-input-block">
              <select
                id="receiptRecordId"
                name="receiptRecordId"
                lay-verify="required"
                lay-filter="receiptRecordId"
                lay-search
              ></select>
            </div>
          </div>
        </div>
        <!-- <div class="layui-col-xs4">
                    <div class="layui-form-item">
                        <label class="layui-form-label">出库仓库</label>
                        <div class="layui-input-block">
                            <input id="warehouseId" name="warehouseId" type="hidden" class="layui-input"/>
                            <input name="receiptWarehouseName" type="text" class="layui-input" readonly/>
                        </div>
                    </div>
                </div> -->
        <div class="layui-col-xs4">
          <div class="layui-form-item">
            <label class="layui-form-label">备注信息</label>
            <div class="layui-input-block">
              <input name="remark" type="text" class="layui-input" readonly />
            </div>
          </div>
        </div>
        <div class="layui-col-xs4">
          <div class="layui-form-item">
            <label class="layui-form-label">领料申请人</label>
            <div class="layui-input-block">
              <input
                name="creatorName"
                type="text"
                class="layui-input"
                readonly
              />
            </div>
          </div>
        </div>
        <div class="layui-col-xs4">
          <div class="layui-form-item">
            <label class="layui-form-label">申请时间</label>
            <div class="layui-input-block">
              <input
                name="createTime"
                type="text"
                class="layui-input"
                readonly
              />
            </div>
          </div>
        </div>
        <div class="layui-form-item">
          <div
            class="addProduceStorageWorkOutDetailForm-title"
            style="margin: 0"
          >
            <h3 class="title">出库明细</h3>
            <button
              class="layui-btn addTable addProductStorageWorkOutDetail"
              type="button"
              style="float: right;margin-top: 10px;"
            >
              添加出库信息
            </button>
          </div>
          <div class="line"></div>
          <!-- 表格 -->
          <table
            class="layui-table"
            id="productStorageWorkDetailTable"
            lay-filter="productStorageWorkDetailTable"
          ></table>
        </div>
      </div>
      <div
        class="layui-form-item text-right"
        id="productStorageWorkDetailSaveBtnDiv"
      >
        <button
          class="layui-btn layui-btn-primary"
          type="button"
          ew-event="closeDialog"
        >
          取消
        </button>
        <button
          class="layui-btn"
          lay-filter="productStorageWorkOutFormSubmit"
          lay-submit
        >
          保存
        </button>
      </div>
    </div>
  </form>
</script>

<!--领料明细表格操作列-->
<script type="text/html" id="productStorageWorkDetailTableBar">
  <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<!-- 领料记录审核、详情弹窗 -->
<script type="text/html" id="receiptRecordEditForm">
  <form lay-filter="receiptRecordEditForm" class="layui-form model-form">
    <input name="id" type="hidden" />
    <div class="layui-col-xs4">
      <div class="layui-form-item">
        <label class="layui-form-label">领料类型</label>
        <div class="layui-input-block">
          <input
            name="inventoryTypeName"
            type="text"
            class="layui-input"
            readonly
          />
        </div>
      </div>
    </div>
    <div class="layui-col-xs4">
      <div class="layui-form-item">
        <label class="layui-form-label">开工单编号</label>
        <div class="layui-input-block">
          <input
            name="workOrderCode"
            type="text"
            class="layui-input"
            readonly
          />
        </div>
      </div>
    </div>
    <div class="layui-col-xs4">
      <div class="layui-form-item">
        <label class="layui-form-label">制造令编号</label>
        <div class="layui-input-block">
          <input name="processCode" type="text" class="layui-input" readonly />
        </div>
      </div>
    </div>
    <div class="layui-col-xs4">
      <div class="layui-form-item">
        <label class="layui-form-label">所属计划</label>
        <div class="layui-input-block">
          <input
            name="productionPlanCode"
            type="text"
            class="layui-input"
            readonly
          />
        </div>
      </div>
    </div>
    <div class="layui-col-xs4">
      <div class="layui-form-item">
        <label class="layui-form-label">仓库类型</label>
        <div class="layui-input-block">
          <input
            name="warehouseTypeName"
            type="text"
            class="layui-input"
            readonly
          />
        </div>
      </div>
    </div>
    <div class="layui-col-xs4">
      <div class="layui-form-item">
        <label class="layui-form-label">领料仓库</label>
        <div class="layui-input-block">
          <input
            name="receiptWarehouseName"
            type="text"
            class="layui-input"
            readonly
          />
        </div>
      </div>
    </div>
    <div class="layui-col-xs4">
      <div class="layui-form-item">
        <label class="layui-form-label">领料料号数</label>
        <div class="layui-input-block">
          <input name="receiptNum" type="text" class="layui-input" readonly />
        </div>
      </div>
    </div>
    <div class="layui-col-xs4">
      <div class="layui-form-item">
        <label class="layui-form-label">审核人</label>
        <div class="layui-input-block">
          <input
            name="auditPersonName"
            type="text"
            class="layui-input"
            readonly
          />
        </div>
      </div>
    </div>
    <div class="layui-col-xs4">
      <div class="layui-form-item">
        <label class="layui-form-label">领料人</label>
        <div class="layui-input-block">
          <input name="creatorName" type="text" class="layui-input" readonly />
        </div>
      </div>
    </div>
    <div class="layui-col-xs4">
      <div class="layui-form-item">
        <label class="layui-form-label">描述</label>
        <div class="layui-input-block">
          <input name="remark" type="text" class="layui-input" />
        </div>
      </div>
    </div>
    <div class="layui-col-xs4">
      <div class="layui-form-item">
        <label class="layui-form-label">审核结果</label>
        <div class="layui-input-block">
          <input name="auditResult" type="text" class="layui-input" />
        </div>
      </div>
    </div>
    <div class="layui-form-item" style="margin-left: 20px;">
      <div class="addProduceStorageWorkOutDetailForm-title">
        <h3 class="title">领料明细</h3>
      </div>
      <div class="line"></div>
      <!-- 表格 -->
      <table
        class="layui-table"
        id="receiptRecordDetailEditTable"
        lay-filter="receiptRecordDetailEditTable"
      ></table>
    </div>
    <div
      class="layui-form-item text-right"
      id="productStorageWorkOutFormAuditDiv"
    >
      <button
        class="layui-btn"
        lay-filter="auditSuccessBtn"
        type="button"
        lay-submit
      >
        通过
      </button>
      <button
        class="layui-btn layui-btn-danger"
        lay-filter="auditFailBtn"
        type="button"
        lay-submit
      >
        驳回
      </button>
    </div>
  </form>
</script>

<!--物料弹窗-->
<script type="text/html" id="productDetailForm">
  <div class="layui-fluid">
    <div class="layui-card">
      <div class="layui-card-body">
        <!-- 头部操作栏 -->
        <div class="layui-form toolbar">
          <div class="layui-form-item">
            <div class="layui-inline">
              <button id="productDetailConfirm" class="layui-btn icon-btn">
                确认选择
              </button>
            </div>
          </div>
        </div>
        <!-- 表格 -->
        <div class="scroll-table-4-5">
          <table
            class="layui-table"
            id="productDetailTable"
            lay-filter="productDetailTable"
          ></table>
        </div>
      </div>
    </div>
  </div>
</script>
<!-- js部分 -->
<script>
  layui.use(
    [
      "layer",
      "form",
      "table",
      "laydate",
      "admin",
      "laytpl",
      "tableTreeDj",
      "config",
    ],
    function () {
      var $ = layui.jquery;
      var layer = layui.layer;
      var laydate = layui.laydate;
      var table = layui.table;
      var form = layui.form;
      var config = layui.config;
      var admin = layui.admin;
      var tableTree = layui.tableTreeDj;
      laydate.render({
        elem: '#pTime',
        type: 'date',
        range: true,
        done: function (value, date, endDate) {
          if (value) {
            var dateValue = value.split(" - ");
            $("input[name='startCreateTime']").val(dateValue[0] + " 00:00:00");
            $("input[name='endCreateTime']").val(dateValue[1] + " 23:59:59");
          } else {
            $("input[name='startCreateTime']").val("");
            $("input[name='endCreateTime']").val("");
          }
        }
      });
      //出库类型列表
      admin.initDataSelect(
        "enterprisecab/warehouse/admin/warehouseInventoryType/list",
        {
          limit: 9999,
          inventoryType: "out",
        },
        "queryOutTypeId",
        null,
        "出库类型",
        null,
        null
      );

      // 渲染表格
      var insTb = table.render({
        id: "#productStorageWorkOutTable",
        elem: "#productStorageWorkOutTable",
        url:
          config.base + "enterprise/storage/admin/productStorageWorkOut/list",
        page: true,
        cellMinWidth: 100,
        cols: [
          [
            { type: "numbers", title: "序号", align: "center" },
            { field: "code", title: "出库作业编号", align: "center" },
            {
              field: "receiptRecordCode",
              title: "申请单编号",
              align: "center",
            },
            {
              field: "receiptRecordCreatorName",
              align: "center",
              title: "申请人",
            },
            // { field: "warehouseName", align: "center", title: "出库仓库" },
            { field: "outTypeName", align: "center", title: "出库类型" },
            { field: "creatorName", align: "center", title: "作业人" },
            {
              field: "createTime",
              align: "center",
              title: "作业时间",
              width: 180,
            },
            {
              align: "center",
              toolbar: "#receiptRecordTabBar",
              title: "操作",
              width: 120,
            },
          ],
        ],
        done: function (res, curr, count) {},
      });

      let materialData = [];

      //渲染下拉
      form.render("select");

      // 工具条点击事件
      table.on("tool(productStorageWorkOutTable)", function (obj) {
        var data = obj.data;
        if (obj.event === "audit") {
          //审核
          showModel(data, 1);
        } else if (obj.event === "detail") {
          //详情
          // showModel(data, 2);
          admin.open({
            type: 1,
            area: ["1500px", "90%"],
            style: "font-size: 20px;",
            title: "出库作业详情",
            content: $("#productStorageWorkOutForm").html(),
            success: function () {
              $(".addProductStorageWorkOutDetail").hide();
              $("#productStorageWorkDetailSaveBtnDiv").hide();
              form.val("productStorageWorkOutForm", data);
              admin.initDataSelect(
                "enterprisecab/warehouse/admin/warehouseInventoryType/list",
                {
                  limit: 9999,
                  inventoryType: "out",
                },
                "outTypeId",
                data.outTypeId,
                "出库类型",
                null,
                null
              );

              let productInventoryDetailList = [];

              if (data.outTypeId == 14) {
                admin.initDataSelect(
                  "enterprise/receiptRecord/admin/receiptRecordOther/list",
                  { limit: 9999 },
                  "receiptRecordId",
                  data.receiptRecordId,
                  "出库申请单",
                  "code",
                  null
                );
              } else {
                //出库申请单列表
                admin.initDataSelect(
                  "enterprise/receiptRecord/admin/receiptRecord/list",
                  { limit: 9999 },
                  "receiptRecordId",
                  data.receiptRecordId,
                  "出库申请单",
                  "code",
                  null
                );
              }

              admin.req(
                "enterprise/receiptRecord/admin/receiptRecord/get",
                { id: data.receiptRecordId },
                function (res) {
                  layer.closeAll("loading");
                  if (res.code == 200) {
                    $("#warehouseId").val(res.data.receiptWarehouse);
                    form.val("productStorageWorkOutForm", res.data);
                    //出库信息列表
                    materialDataList = res.data.receiptRecordDetailList;
                    materialDataList.forEach((item) => {
                      item.receiptWarehouse = res.data.receiptWarehouse;
                      item.receiptWarehouseCode = res.data.receiptWarehouseCode;
                      item.receiptWarehouseName = res.data.receiptWarehouseName;
                    });

                    //清空出库明细
                    // table.reload('productStorageWorkDetailTable', {data: []});
                    //清空选择的物料数据
                    materialData = [];
                    //产品库存详情列表
                    admin.req(
                      "enterprise/storage/admin/productInventoryDetail/list",
                      {
                        limit: 9999,
                        warehouseId: res.data.receiptWarehouse,
                      },
                      function (res) {
                        layer.closeAll("loading");
                        if (res.code == 200) {
                          productInventoryDetailList = res.data;
                          console.log(11111, productInventoryDetailList);
                          table.reload("productStorageWorkDetailTable", {
                            data: data.productStorageWorkOutDetailList,
                          });
                        } else {
                          layer.msg(res.msg, { icon: 2 });
                        }
                      },
                      "GET"
                    );
                  } else {
                    layer.msg(res.msg, { icon: 2 });
                  }
                },
                "GET"
              );
              console.log(123, data);

              //出库明细表格
              table.render({
                elem: "#productStorageWorkDetailTable",
                data: data.productStorageWorkOutDetailList,
                cellMinWidth: 100,
                page: false,
                cols: [
                  [
                    { type: "numbers", width: 50, title: "序号" },
                    { field: "skuCode", title: "物料编码", align: "center" },
                    {
                      field: "skuName",
                      title: "出库物料名称",
                      align: "center",
                      width: 150,
                    },
                    {
                      field: "skuSpec",
                      title: "规格码",
                      align: "center",
                      width: 150,
                    },

                    {
                      field: "warehouseShelfSpaceCode",
                      title: "出库库位",
                      align: "center",
                      width: 150,
                      // templet: (d) => {
                      //     let options = productInventoryDetailList
                      //         .filter(item => item.skuCode === d.skuCode)
                      //         .map(item => ({
                      //             value: item.warehouseShelfSpaceId,
                      //             label: item.warehouseShelfSpaceCode
                      //         }));
                      //     return admin.setTableSelect('warehouseShelfSpaceId', options, false, 'warehouseShelfSpaceId')(d);
                      // }
                    },
                    {
                      field: "palletBoxCode",
                      title: "载具编号",
                      align: "center",
                      width: 150,
                      templet: (d) => {
                        return d.palletBoxCode ? d.palletBoxCode : "无料箱";
                      },
                      // templet: (d) => {
                      //     const options = []
                      //     if (d.warehouseShelfSpaceId) {
                      //         productInventoryDetailList.forEach(item => {
                      //             if (item.warehouseShelfSpaceId === d.warehouseShelfSpaceId) {
                      //                 options.push({
                      //                     value: item.palletBoxId,
                      //                     label: item.palletBoxCode
                      //                 })
                      //             }
                      //         });
                      //     }
                      //     return admin.setTableSelect('palletBoxId', options, false, 'palletBoxId')(d);
                      // }
                    },
                    {
                      field: "warehouseName",
                      title: "仓库名称",
                      align: "center",
                    },

                    { field: "mainUnitName", title: "主单位", align: "center" },
                    {
                      field: "receiptNum",
                      title: "申请数量",
                      align: "center",
                      width: 140,
                    },
                    {
                      field: "outNum",
                      title: "出库数量",
                      align: "center",
                      width: 140,
                      edit: "text",
                    },
                    {
                      field: "remark",
                      title: "备注",
                      align: "center",
                      width: 160,
                      edit: "text",
                    },
                  ],
                ],
                done: function (res, curr, count) {
                  $(
                    ".layui-table-body, .layui-table-box, .layui-table-cell"
                  ).css("overflow", "visible"); //显示高于表格
                  admin.tableSelectChange(
                    "productStorageWorkDetailTable",
                    "warehouseShelfSpaceId",
                    () => {
                      table.reload("productStorageWorkDetailTable");
                    }
                  );
                  admin.tableSelectChange(
                    "productStorageWorkDetailTable",
                    "palletBoxId"
                  );
                },
              });
            },
          });
        }
      });

      //监听排序
      table.on("sort(productStorageWorkOutTable)", function (obj) {
        table.reload("productStorageWorkOutTable", {
          initSort: obj,
          where: {
            sort: obj.field,
            order: obj.type,
          },
        });
      });

      // 搜索
      form.on("submit(formSubSearchLog)", function (data) {
        insTb.reload({ where: data.field, page: { curr: 1 } }, "data");
      });

      // 重置搜索
      form.on("submit(resets)", (data) => {
        $(".lay-header").find("select").val("");
        $(".lay-header").find("input").val("");
        let field = data.field;
        for (let key in field) {
          field[key] = "";
        }
        insTb.reload({ where: field, page: { curr: 1 } }, "data");
      });

      // 添加按钮点击事件2
      $("#productStorageWorkOutAdd").click(function () {
        //    showEditModel();
        openForm("add");
      });
      function openForm(eventName, data) {
        const titleObj = {
          add: "添加出库作业",
          edit: "修改出库作业",
          detail: "查看出库作业",
        };
        admin.formOpen({
          area: ["90%", "90%"],
          offset: ["30px", "5%"],
          title: titleObj[eventName],
          path: "components/storage/productStorageWorkOutForm.html",
          success: function () {
            parentData.eventName = eventName;
            parentData.data = data;
          },
        });
      }
      // 出库作业弹窗
      function showEditModel() {
        admin.open({
          type: 1,
          area: ["90%", "90%"],
          offset: ["30px", "5%"],
          style: "font-size: 20px;",
          title: "添加出库作业",
          content: $("#productStorageWorkOutForm").html(),
          success: function () {
            //出库类型列表
            admin.initDataSelect(
              "enterprisecab/warehouse/admin/warehouseInventoryType/list",
              {
                limit: 9999,
                inventoryType: "out",
              },
              "outTypeId",
              null,
              "出库类型",
              null,
              null
            );

            //出库申请单列表
            admin.initDataSelect(
              "enterprise/receiptRecord/admin/receiptRecord/list",
              { limit: 9999 },
              "receiptRecordId",
              null,
              "出库申请单",
              "code",
              null
            );

            //出库申请单选择事件
            let materialDataList = [];
            let productInventoryDetailList = [];
            form.on("select(receiptRecordId)", function (selectData) {
              admin.req(
                "enterprise/receiptRecord/admin/receiptRecord/get",
                { id: selectData.value },
                function (res) {
                  layer.closeAll("loading");
                  if (res.code == 200) {
                    $("#warehouseId").val(res.data.receiptWarehouse);
                    form.val("productStorageWorkOutForm", res.data);
                    //出库信息列表
                    materialDataList = res.data.receiptRecordDetailList;
                    materialDataList.forEach((item) => {
                      item.receiptWarehouse = res.data.receiptWarehouse;
                      item.receiptWarehouseCode = res.data.receiptWarehouseCode;
                      item.receiptWarehouseName = res.data.receiptWarehouseName;
                    });
                    //清空出库明细
                    //清空选择的物料数据
                    materialData = [];
                    //产品库存详情列表
                    admin.req(
                      "enterprise/storage/admin/productInventoryDetail/list",
                      {
                        limit: 9999,
                        warehouseId: res.data.receiptWarehouse,
                      },
                      function (res1) {
                        layer.closeAll("loading");
                        console.log(11, [...res1.data]);

                        if (res1.code == 200) {
                          productInventoryDetailList = res1.data;
                          table.reload("productStorageWorkDetailTable", {
                            data: [],
                          });
                        } else {
                          layer.msg(res1.msg, { icon: 2 });
                        }
                      },
                      "GET"
                    );
                  } else {
                    layer.msg(res.msg, { icon: 2 });
                  }
                },
                "GET"
              );
            });

            //出库明细表格
            table.render({
              elem: "#productStorageWorkDetailTable",
              data: [],
              cellMinWidth: 100,
              page: false,
              cols: [
                [
                  { type: "numbers", width: 50, title: "序号" },
                  { field: "productDetailId", title: "物料ID", hide: true },
                  { field: "skuCode", title: "出库料号", align: "center" },
                  {
                    field: "skuName",
                    title: "出库物料名称",
                    align: "center",
                    width: 150,
                  },
                  {
                    field: "skuSpec",
                    title: "规格码",
                    align: "center",
                    width: 150,
                  },

                  {
                    field: "warehouseShelfSpaceId",
                    title: "出库库位",
                    align: "center",
                    width: 150,
                    templet: (d) => {
                      const options = productInventoryDetailList
                        .filter((item) => item.skuCode === d.skuCode)
                        .map((item) => ({
                          value: item.warehouseShelfSpaceId,
                          label: item.warehouseShelfSpaceCode,
                        }));
                      return admin.setTableSelect(
                        "warehouseShelfSpaceId",
                        options,
                        false,
                        "warehouseShelfSpaceId"
                      )(d);
                    },
                  },
                  {
                    field: "palletBoxId",
                    title: "载具编号",
                    align: "center",
                    width: 150,
                    templet: (d) => {
                      const options = [];
                      if (d.warehouseShelfSpaceId) {
                        productInventoryDetailList.forEach((item) => {
                          if (
                            item.warehouseShelfSpaceId ===
                            d.warehouseShelfSpaceId
                          ) {
                            options.push({
                              value: item.palletBoxId,
                              label: item.palletBoxCode,
                            });
                          }
                        });
                      }
                      return admin.setTableSelect(
                        "palletBoxId",
                        options,
                        false,
                        "palletBoxId"
                      )(d);
                    },
                  },
                  { field: "mainUnitName", title: "主单位", align: "center" },
                  {
                    field: "receiptNum",
                    title: "申请数量",
                    align: "center",
                    width: 140,
                  },
                  {
                    field: "outNum",
                    title: "出库数量",
                    align: "center",
                    width: 140,
                    edit: "text",
                  },
                  {
                    field: "remark",
                    title: "备注",
                    align: "center",
                    width: 160,
                    edit: "text",
                  },
                  {
                    align: "center",
                    toolbar: "#productStorageWorkDetailTableBar",
                    title: "操作",
                    width: 100,
                  },
                ],
              ],
              done: function (res, curr, count) {
                $(".layui-table-body, .layui-table-box, .layui-table-cell").css(
                  "overflow",
                  "visible"
                ); //显示高于表格
                admin.tableSelectChange(
                  "productStorageWorkDetailTable",
                  "warehouseShelfSpaceId",
                  () => {
                    table.reload("productStorageWorkDetailTable");
                  }
                );
                admin.tableSelectChange(
                  "productStorageWorkDetailTable",
                  "palletBoxId"
                );
              },
            });

            // 领料明细工具条点击事件
            table.on("tool(productStorageWorkDetailTable)", function (obj) {
              let rowData = obj.data;
              let list = materialData;
              if (obj.event === "save") {
                // 保存
                let planProductionQuantity = $(this)
                  .parents("td")
                  .siblings()
                  .find(".planProductionQuantity")
                  .val();
                let outputQuantity = $(this)
                  .parents("td")
                  .siblings()
                  .find(".outputQuantity")
                  .val();
                if (planProductionQuantity == "") {
                  layer.msg("请输入计划排产数量", { icon: 2 });
                  return false;
                }
                if (outputQuantity == "") {
                  layer.msg("请输入排产数量", { icon: 2 });
                  return false;
                }
                list.forEach((item, index) => {
                  if (rowData.deviceCode === item.deviceCode) {
                    list[index].status = "yes";
                    list[index].outputQuantity = outputQuantity;
                    list[index].planProductionQuantity = planProductionQuantity;
                  }
                });
              } else if (obj.event === "del") {
                //删除
                list = table.cache["productStorageWorkDetailTable"];
                list.forEach((item, index) => {
                  if (rowData.skuCode === item.skuCode) {
                    list.splice(index, 1);
                  }
                });
                //删除后更新数据
              }
              // 渲染表格
              table.reload("productStorageWorkDetailTable", {
                data: list,
              });
            });

            // 添加出库信息
            $(".addProductStorageWorkOutDetail").click(function () {
              //判断是否选择出库申请单
              var receiptRecordId = $("#receiptRecordId").val();
              if (receiptRecordId == "" || receiptRecordId == undefined) {
                layer.msg("请选择出库申请单", { icon: 3, time: 1000 });
                return;
              }
              let arrList = [];
              materialData.forEach((item) => {
                arrList.push(item.skuCode);
              });
              var productDetailInsTb = admin.open({
                type: 1,
                title: "物料列表",
                area: "75%",
                offset: ["120px", "350px"],
                content: $("#productDetailForm").html(),
                success: function () {
                  // 渲染表格
                  var productDetailTable = table.render({
                    elem: "#productDetailTable",
                    data: materialDataList,
                    cellMinWidth: 100,
                    cols: [
                      [
                        { type: "checkbox" },
                        {
                          field: "productDetailId",
                          title: "物料ID",
                          hide: true,
                        },
                        {
                          field: "skuCode",
                          title: "物料编码",
                          align: "center",
                        },
                        {
                          field: "skuName",
                          title: "物料名称",
                          align: "center",
                        },
                        {
                          field: "skuSpec",
                          title: "物料规格",
                          align: "center",
                        },
                        {
                          field: "materialNatureName",
                          title: "物料类别性质",
                          align: "center",
                        },
                        {
                          field: "productTypeName",
                          title: "物料类别",
                          align: "center",
                        },
                        {
                          field: "receiptNum",
                          title: "领取数量",
                          align: "center",
                        },
                        {
                          field: "unitName",
                          title: "计量单位",
                          align: "center",
                        },
                        {
                          field: "baseUnitName",
                          title: "基础单位",
                          align: "center",
                        },
                        {
                          field: "createTime",
                          title: "创建时间",
                          align: "center",
                          width: 170,
                        },
                      ],
                    ],
                    done: function (res, curr, count) {
                      // 如果选择过的checkbox 则通过code标识判断 禁用下拉框
                      // let allCheck = true;
                      // for (let item in res.data) {
                      //     if (arrList.indexOf(res.data[item].skuCode) !== -1) {
                      //         allCheck = false;
                      //     }
                      //     break;
                      // }
                      // if (!allCheck) {
                      //     $(".layui-table-header").find("input[name = 'layTableCheckbox'][lay-filter='layTableAllChoose']").each(function () {
                      //         $(this).attr("disabled", 'disabled').next().removeClass("layui-form-checked");
                      //         form.render('checkbox');
                      //     });
                      // }
                      // let i = 0;
                      // $(".layui-table-body.layui-table-main").find("input[name='layTableCheckbox']").each(function () {
                      //     if (arrList.indexOf(res.data[i].skuCode) != -1) {
                      //         $(this).attr("disabled", 'disabled').removeAttr("checked");
                      //         $(this).parents("tr").addClass("disabledBg");
                      //         form.render('checkbox');
                      //     }
                      //     i++;
                      // });
                      // i = 0;
                      // $(".layui-table-fixed.layui-table-fixed-l").find(".layui-table-body").find("input[name='layTableCheckbox']").each(function () {
                      //     if (arrList.indexOf(res.data[i].skuCode) != -1) {
                      //         $(this).attr("disabled", 'disabled').removeAttr("checked");
                      //         $(this).parents("tr").addClass("disabledBg");
                      //         form.render('checkbox');
                      //     }
                      //     i++;
                      // });
                    },
                  });

                  // 确认选择
                  $("#productDetailConfirm").click(function () {
                    let checkStatus = table.checkStatus("productDetailTable"); //test即为基础参数id对应的值
                    let productDetailCheckData = checkStatus.data;
                    console.log(
                      "checkStatus,",
                      checkStatus,
                      productDetailCheckData
                    );
                    if (checkStatus.data.length == 0) {
                      layer.msg("请选择物料", { icon: 2, time: 1000 });
                    } else {
                      let list = materialData;
                      console.log([...list]);
                      console.log([...productDetailCheckData]);
                      // let filterList = list.filter((item) => {
                      //     return item.materialSkuCode == productDetailCheckData[0].skuCode
                      // });
                      // if (filterList.length > 0) {
                      //     layer.msg('当前选择的物料已存在', {icon: 2});
                      //     return false;
                      // }
                      productDetailCheckData.forEach((v) => {
                        if (
                          list.some((v1) => v1.receiptRecordDetailId == v.id)
                        ) {
                        } else {
                          list.push({
                            receiptRecordDetailId: v.id,
                            productDetailId: v.productDetailId,
                            skuCode: v.skuCode,
                            skuName: v.skuName,
                            skuSpec: v.skuSpec,
                            warehouseId: v.receiptWarehouse,
                            receiptWarehouseCode: v.receiptWarehouseCode,
                            receiptWarehouseName: v.receiptWarehouseName,
                            productTypeName: v.productTypeName,
                            receiptNum: v.receiptNum,
                            mainUnitName: v.unitName,
                            baseUnitName: v.baseUnitName,
                            createTime: v.createTime,
                          });
                        }
                      });
                      list = list.filter((v) => {
                        return productDetailCheckData.some(
                          (v1) => v.receiptRecordDetailId == v1.id
                        );
                      });
                      // productDetailCheckData.forEach((item) => {
                      //     list.push({
                      //         receiptRecordDetailId: item.id,
                      //         productDetailId: item.productDetailId,
                      //         skuCode: item.skuCode,
                      //         skuName: item.skuName,
                      //         skuSpec: item.skuSpec,
                      //         warehouseId: item.receiptWarehouse,
                      //         receiptWarehouseCode: item.receiptWarehouseCode,
                      //         receiptWarehouseName: item.receiptWarehouseName,
                      //         productTypeName: item.productTypeName,
                      //         receiptNum: item.receiptNum,
                      //         unitName: item.unitName,
                      //         baseUnitName: item.baseUnitName,
                      //         createTime: item.createTime,
                      //     });

                      //选择的物料信息赋值
                      materialData = list;
                      console.info([...list], 9090);
                      layer.close(productDetailInsTb);
                      // 领料料号数
                      $("#receiptNum").val(list.length);
                      // 渲染表格
                      table.reload("productStorageWorkDetailTable", {
                        data: list,
                      });
                      // });
                    }
                  });
                },
              });
            });
          },
          finish: function () {
            table.reload("productStorageWorkOutTable", {});
          },
        });
      }

      // 领料记录审核、详情弹窗
      function showModel(data, type) {
        admin.open({
          type: 1,
          area: ["1500px", "90%"],
          offset: ["80px", "320px"],
          style: "font-size: 20px;",
          title: type === 1 ? "领料记录审核" : "领料记录详情",
          content: $("#receiptRecordEditForm").html(),
          success: function () {
            //详情页面-隐藏按钮
            if (type === 2) {
              $("#productStorageWorkOutFormAuditDiv").hide();
            }
            //领料记录数据回显
            console.log({ ...data });

            form.val("receiptRecordEditForm", data);
            form.render();
            //领料明细表格
            table.render({
              elem: "#receiptRecordDetailEditTable",
              data: data.receiptRecordDetailList,
              cellMinWidth: 100,
              page: false,
              cols: [
                [
                  { type: "numbers", width: 50, title: "序号" },
                  { field: "skuCode", title: "物料编码", align: "center" },
                  {
                    field: "skuName",
                    title: "物料名称",
                    align: "center",
                    width: 150,
                  },
                  {
                    field: "skuSpec",
                    title: "物料规格",
                    align: "center",
                    width: 150,
                  },
                  {
                    field: "materialNatureName",
                    title: "物料类别性质",
                    align: "center",
                    width: 140,
                  },
                  {
                    field: "productTypeName",
                    title: "物料类别",
                    align: "center",
                    width: 140,
                  },
                  { field: "baseUnitName", title: "基础单位", align: "center" },
                  { field: "unitName", title: "计量单位", align: "center" },
                  {
                    field: "receiptNum",
                    title: "领取数量",
                    align: "center",
                    width: 140,
                    edit: "text",
                  },
                  {
                    field: "remark",
                    title: "备注",
                    align: "center",
                    width: 160,
                    edit: "text",
                  },
                ],
              ],
            });

            //审核通过
            form.on("submit(auditSuccessBtn)", function (data) {
              data.field.status = 2; //待领料
              // 更新
              admin.req(
                "enterprise/receiptRecord/admin/receiptRecord/update",
                data.field,
                function (res) {
                  layer.closeAll("loading");
                  if (res.code == 200) {
                    layer.msg(res.msg, { icon: 1 });
                    layer.closeAll();
                    insTb.reload("productStorageWorkOutTable");
                  } else {
                    layer.msg(res.msg, { icon: 2 });
                  }
                },
                "POST"
              );
              return false;
            });

            //审核驳回
            form.on("submit(auditFailBtn)", function (data) {
              data.field.status = 4; //驳回
              // 更新
              admin.req(
                "enterprise/receiptRecord/admin/receiptRecord/update",
                data.field,
                function (res) {
                  layer.closeAll("loading");
                  if (res.code == 200) {
                    layer.msg(res.msg, { icon: 1 });
                    layer.closeAll();
                    insTb.reload("productStorageWorkOutTable");
                  } else {
                    layer.msg(res.msg, { icon: 2 });
                  }
                },
                "POST"
              );
              return false;
            });
          },
          finish: function () {
            table.reload("productStorageWorkOutTable", {});
          },
        });
      }

      // 提交数据
      form.on("submit(productStorageWorkOutFormSubmit)", function (d) {
        let flag = false;
        if (materialData.length == 0) {
          layer.msg("请添加出库信息", { icon: 2 });
          return false;
        }
        //领料明细列表
        var detailList = table.cache["productStorageWorkDetailTable"];
        detailList.forEach((detail) => {
          if (
            detail.receiptNum === "" ||
            detail.receiptNum === null ||
            detail.receiptNum === undefined
          ) {
            layer.msg(`物料【${detail.skuName}】领取数量不能为空`, { icon: 2 });
            flag = true;
            return false;
          }
        });
        // 控制不能提交为空的数据
        if (flag) {
          return false;
        }
        d.field.productStorageWorkOutDetailList = detailList;
        // 提交计划
        admin.req(
          "enterprise/storage/admin/productStorageWorkOut/add",
          JSON.stringify(d.field),
          function (res) {
            layer.closeAll("loading");
            if (res.code == 200) {
              // 提交成功清空缓存数据
              materialData = [];
              layer.msg(res.msg, { icon: 1 });
              layer.closeAll();
              insTb.reload("productStorageWorkOutTable");
            } else {
              layer.msg(res.msg, { icon: 2 });
            }
          },
          "POST",
          true,
          "application/json; charset=utf-8"
        );
        return false;
      });


      /**
       * 导出模块
       */
      $('#storageWorkInfoBtnExport').click(function () {
        let queryOutTypeId = $('#queryOutTypeId').val();
        let code = $('#code').val();
        // 创建一个对象来保存所有可能的查询参数
        let queryParams = {
          outTypeId: queryOutTypeId,
          code: code
        };

        // 过滤掉值为 undefined 的属性
        queryParams = Object.keys(queryParams)
                .filter(key => queryParams[key] !== undefined && queryParams[key] !== '')
                .reduce((obj, key) => {
                  obj[key] = queryParams[key];
                  return obj;
                }, {});

        // 将过滤后的参数对象转换为查询字符串
        let queryString = new URLSearchParams(queryParams).toString();

        // 获取当前日期和时间
        let now = new Date();
        let year = now.getFullYear();
        let month = String(now.getMonth() + 1).padStart(2, '0'); // 注意：getMonth() 返回值是 0-11
        let day = String(now.getDate()).padStart(2, '0');
        let hour = String(now.getHours()).padStart(2, '0');
        let minute = String(now.getMinutes()).padStart(2, '0');
        let second = String(now.getSeconds()).padStart(2, '0');

        // 格式化日期和时间为 YYYYMMDD_HHMMSS 形式
        let formattedDateTime = `${year}${month}${day}_${hour}${minute}${second}`;

        // 设置下载文件名为 "产品数据_YYYYMMDD_HHMMSS.xls"
        let fileName = `出库作业列表数据_${formattedDateTime}.xls`;

        // 创建完整的URL，包括查询参数和文件名作为额外参数（如果后端支持的话）
        let fullUrl = config.base + 'enterprise/storage/admin/productStorageWorkOut/export?' + queryString + '&fileName=' + encodeURIComponent(fileName);

        // 使用 window.open 打开新页面进行下载
        window.open(fullUrl + '&Authorization=Bearer ' + encodeURIComponent(config.getToken()), '_blank');
        // 注意：这里假设后端能够处理 fileName 参数，并根据它设置响应头中的 Content-Disposition 来指定下载文件名。
        // 如果后端不支持通过 URL 参数指定文件名，你可能需要调整后端代码来接受这种请求方式。
      });



    }
  );
</script>
<style>
  .addProduceStorageWorkOutDetailForm-title {
    width: 100%;
    margin-left: 20px;
  }

  .addProduceStorageWorkOutDetailForm-title .title,
  .title {
    display: inline-block;
    font-size: 16px;
    font-weight: bold;
    color: #333333;
    line-height: 19px;
    position: relative;
    padding: 6px 0 19px 0;
  }

  .addProduceStorageWorkOutDetailForm-title .title:after,
  .title:after {
    content: "";
    display: block;
    position: absolute;
    left: 0;
    bottom: 0;
    width: calc(100% + 6px);
    height: 3px;
    background: #0a8b0a;
  }

  .addTable {
    height: 30px;
    margin-left: 30px;
    line-height: 30px;
    padding: 0 10px;
  }
</style>
